﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CRMAdminDashboard.CrmSvc;
using System.Collections;

namespace CRMAdminDashboard
{
    public partial class FormCompareRoles : Form, IUtilityForm
    {

        #region Constants

        private const string RES_ROLESFORM_LSTHELP = "RES_ROLESFORM_LSTHELP";
        private const string RES_ROLESFORM_COMPAREHELP = "RES_ROLESFORM_COMPAREHELP";
        private const string RES_ROLESFORM_CREATEEQUIVHELP = "RES_ROLESFORM_CREATEEQUIVHELP";
        private const string RES_ROLESFORM_SHOWHELP = "RES_ROLESFORM_SHOWHELP";
        private const string RES_ROLESFORM_SUBTRACTHELP = "RES_ROLESFORM_SUBTRACTHELP";

        #endregion

        #region Fields

        /// <summary>
        /// Static pointer to my console
        /// </summary>
        private static TextBox _logWindow;

        /// <summary>
        /// True when the parent form has ordered to close
        /// </summary>
        private bool _closeFromParent;

        /// <summary>
        /// Code behind
        /// </summary>
        private HelperCompareRoles _helper;

        #endregion

        #region Entry Points

        /// <summary>
        /// Standard constructor
        /// </summary>
        public FormCompareRoles(CachingCrmService svcHandle)
        {
            InitializeComponent();
            this._helper = new HelperCompareRoles(svcHandle);
            EnableControls();
            cbCompareMode.SelectedIndex = 0;
            _logWindow = txtOutput;
        }

        /// <summary>
        /// Called by the Parent form when logging out. Will force this form shut.
        /// </summary>
        public void ParentClose()
        {
            this._closeFromParent = true;
            this.Close();
            this._closeFromParent = false;
        }

        /// <summary>
        /// Write on the console
        /// </summary>
        /// <param name="logInMain">Write also on the parent's console</param>
        public static void WriteLog(bool logInMain, string msg)
        {
            _logWindow.AppendText(msg);
            if (logInMain)
            {
                FormLogin.WriteLog(msg);
            }
        }

        /// <summary>
        /// Write an exception on the console
        /// </summary>
        /// <param name="logInMain">Write also on the parent's console</param>
        public static void WriteLog(bool logInMain, Exception ex)
        {
            ClearLog();
            WriteLog(logInMain, FormLogin.FormatException(ex) + Environment.NewLine + Environment.NewLine);
        }

        /// <summary>
        /// Clear the console
        /// </summary>
        public static void ClearLog()
        {
            _logWindow.Clear();
        }

        #endregion

        #region Events

        private void FormCompareRoles_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!this._closeFromParent)
            {
                ((FormLogin)this.Owner).ForceLogout();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FormCompareRoles_Load(object sender, EventArgs e)
        {
            lblHelpList.Text = Program.GetResString(RES_ROLESFORM_LSTHELP);
            btnCompare.Text = Program.GetResString(RES_ROLESFORM_COMPAREHELP);
            btnCreateEquiv.Text = Program.GetResString(RES_ROLESFORM_CREATEEQUIVHELP);
            btnShowLeftPrivileges.Text = Program.GetResString(RES_ROLESFORM_SHOWHELP);
            btnSubtract.Text = Program.GetResString(RES_ROLESFORM_SUBTRACTHELP);
        }

        private void lstSelectedIndexChanged(object sender, EventArgs e)
        {
            int selLeft = lstLeft.SelectedItems.Count;
            if (selLeft == 0)
            {
                lblLeftSelected.Text = null;
            }
            else
            {
                lblLeftSelected.Text = selLeft.ToString() + " selected";
            }

            int selRight = lstRight.SelectedItems.Count;
            if (selRight == 0)
            {
                lblRightSelected.Text = null;
            }
            else
            {
                lblRightSelected.Text = selRight.ToString() + " selected";
            }
            this.EnableControls();
        }

        private void btnGetRoles_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnGetRoles.Enabled = false;
                this._helper.GetRoles(lstLeft, lstRight);
                if (this._helper.BuFilter != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Warning! BU Filter ON (");
                    foreach (BusinessUnit bu in this._helper.BuFilter.Values)
                    {
                        sb.Append(bu.Name + ", ");
                    }
                    sb.Length = sb.Length - 2;
                    sb.Append(")");
                    lblWarning.Text = sb.ToString();
                    btnDumpRoles.Text = "&Save Filtered Roles as XML file...";
                }
                else
                {
                    lblWarning.Text = null;
                    btnDumpRoles.Text = "&Save All Roles as XML file...";
                }
            }
            finally
            {
                btnGetRoles.Enabled = true;
                EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        private void btnDumpRoles_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnDumpRoles.Enabled = false;
                this._helper.DumpAllRoles();
            }
            finally
            {
                btnDumpRoles.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnCompare_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnCompare.Enabled = false;
                this._helper.CompareRoles(
                    new ArrayList(lstLeft.SelectedItems).Cast<SystemRole>(),
                    new ArrayList(lstRight.SelectedItems).Cast<SystemRole>(),
                    cbCompareMode.SelectedIndex);
            }
            finally
            {
                btnCompare.Enabled = true;
                EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSelectUserLeft_Click(object sender, EventArgs e)
        {
            try
            {
                btnSelectUserLeft.Enabled = false;
                SelectByUser(lstLeft);
            }
            finally
            {
                btnSelectUserLeft.Enabled = true;
            }
        }

        private void btnSelectUserRight_Click(object sender, EventArgs e)
        {
            try
            {
                btnSelectUserRight.Enabled = false;
                SelectByUser(lstRight);
            }
            finally
            {
                btnSelectUserRight.Enabled = true;
            }
        }

        private void btnShowLeftPrivileges_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnShowLeftPrivileges.Enabled = false;
                this._helper.ShowPrivileges(new ArrayList(lstLeft.SelectedItems).Cast<SystemRole>(), cbCompareMode.SelectedIndex);
            }
            finally
            {
                btnShowLeftPrivileges.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnCreateEquiv_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnCreateEquiv.Enabled = false;
                bool success = this._helper.CreateEquivalent(lstLeft);
                if (success)
                {
                    lstLeft.Items.Clear();
                    lstRight.Items.Clear();
                }
            }
            finally
            {
                btnCreateEquiv.Enabled = true;
                EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSubtract_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnSubtract.Enabled = false;
                bool success = this._helper.SubtractRoles(lstLeft, lstRight);
                if (success)
                {
                    lstLeft.Items.Clear();
                    lstRight.Items.Clear();
                }
            }
            finally
            {
                btnSubtract.Enabled = true;
                EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        #endregion

        #region Local Methods

        /// <summary>
        /// Enable/disable controls accordingly
        /// </summary>
        private void EnableControls()
        {
            if (lstLeft.Items.Count > 0)
            {
                lstLeft.Enabled = true;
                lblLeft.Enabled = true;
                lblLeftSelected.Visible = true;
                lstRight.Enabled = true;
                lblRight.Enabled = true;
                lblRightSelected.Visible = true;
                lblHelpList.Visible = true;
                if (lstLeft.SelectedItems.Count > 0)
                {
                    cbCompareMode.Visible = true;
                    btnShowLeftPrivileges.Visible = true;
                    if (lstRight.SelectedItems.Count > 0)
                    {
                        btnCompare.Visible = true;
                        btnSubtract.Visible = true;
                    }
                    else
                    {
                        btnCompare.Visible = false;
                        btnSubtract.Visible = false;
                    }

                    if (lstLeft.SelectedItems.Count > 1)
                    {
                        btnCreateEquiv.Visible = true;
                    }
                    else
                    {
                        btnCreateEquiv.Visible = false;
                    }
                }
                else
                {
                    btnCompare.Visible = false;
                    cbCompareMode.Visible = false;
                    btnShowLeftPrivileges.Visible = false;
                    btnSubtract.Visible = false;
                }
                btnSelectUserLeft.Visible = true;
                btnSelectUserRight.Visible = true;
                btnDumpRoles.Visible = true;
            }
            else
            {
                lstLeft.Enabled = false;
                lblLeft.Enabled = false;
                lblLeftSelected.Visible = false;
                lstRight.Enabled = false;
                lblRight.Enabled = false;
                lblRightSelected.Visible = false;
                lblHelpList.Visible = false;
                cbCompareMode.Visible = false;
                btnCompare.Visible = false;
                btnCreateEquiv.Visible = false;
                btnSubtract.Visible = false;
                btnSelectUserLeft.Visible = false;
                btnSelectUserRight.Visible = false;
                btnShowLeftPrivileges.Visible = false;
                btnDumpRoles.Visible = false;
            }
        }

        /// <summary>
        /// Select roles owned by user
        /// </summary>
        private void SelectByUser(ListBox lstBox1)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this._helper.SelectByUser(lstBox1);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        #endregion

    }
}
